package my.epoll;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * @author fengbo
 */
public class EventArray {

    private static final int EPOLL_EVENT_SIZE = Native.sizeofEpollEvent();
    private static final int EPOLL_DATA_OFFSET = Native.offsetofEpollData();
    private static final boolean BIG_ENDIAN_NATIVE_ORDER = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;

    private ByteBuffer memory;
    private long memoryAddress;
    private int length;

    public EventArray(int length) {
        if (length < 1) {
            throw new IllegalArgumentException("length must be >= 1 but was " + length);
        }
        this.length = length;
        this.memory = ByteBuffer.allocateDirect(calculateBufferCapacity(length))
                .order(BIG_ENDIAN_NATIVE_ORDER ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
        this.memoryAddress = Native.memoryAddress(memory);
    }

    private static int calculateBufferCapacity(int capacity) {
        return capacity * EPOLL_EVENT_SIZE;
    }

    public long memoryAddress() {
        return memoryAddress;
    }

    public int length() {
        return length;
    }

    public int events(int index) {
        return getInt(index, 0);
    }

    public int fd(int index) {
        return getInt(index, EPOLL_DATA_OFFSET);
    }

    private int getInt(int index, int offset) {
        return memory.getInt(index * EPOLL_EVENT_SIZE + offset);
    }
}
